package rpchandle

import (
	"fmt"

	"smartconn.cc/cubestruct/App/rpchandle/rpcclient"
	"smartconn.cc/cubestruct/App/rpchandle/rpcserver"
	"smartconn.cc/cubestruct/Msg"
	"smartconn.cc/tosone/logstash"
)

// RPCAppEndStart define
func RPCAppEndStart() {
	// Start app-end rpc client which will connect to service-end rpc server
	rpcclient.StartConn()

	// When app-end rpc client connects service-end rpc server, app-end start rpc server
	status := rpcserver.StartConn()

	// When app-end rpc server start successfully, notice service-end rpc client connect the server
	if status == true {
		msg := Msg.APPServerStatus{Done: true}
		var reply bool
		err := rpcclient.Client.Call("Service.ConnectToAPPServer", msg, &reply)
		if err != nil {
			logstash.Error(err.Error())
		} else {
			logstash.Debug(fmt.Sprintf("Service-end rpcClient connet to app-end rpcserver with status: %v", reply))
		}
	}
}

// RPCAppEndStop define
func RPCAppEndStop() {
	// Stop service-end rpc client connecting from app-end rpc server before stop app-end rpc server
	msg := Msg.APPServerStatus{Done: false}
	var reply bool
	rpcclient.Client.Call("Service.DisconnectFromAPPServer", msg, &reply)

	// Stop app-end rpc server
	rpcserver.StopConn()

	// Stop app-end rpc client
	rpcclient.StopConn()
}
